package com.pbs.ui;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.pbs.contact.Contact;
import com.pbs.net.WSF;
import com.pbs.packdata.SenderContactInfo;
import com.pbs.ui.dialog.Dialog;
import com.pbs.ui.dialog.Dialog.Type;
import com.pbs.utils.ContactProvider;
import com.pbs.utils.MyXStream;

public class SenderContactListActivity extends Activity implements
		OnItemClickListener {
	private ArrayList<SenderContactInfo> items = new ArrayList<SenderContactInfo>();
	private ListView lv;
	private ArrayAdapter<SenderContactInfo> aa;
	ContactProvider cp;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sender_list);
		lv = (ListView) findViewById(R.id.List);
		try {
			cp = new ContactProvider();
			cp.setCr(getContentResolver());
			cp.setCur(getContentResolver().query(
					ContactsContract.Contacts.CONTENT_URI, null, null, null,
					"display_name ASC"));
			items = WSF.getSenderList(AccountManagerScreen.getUsername());
			aa = new ArrayAdapter<SenderContactInfo>(this,
					R.layout.item_sender_info, items) {
				@Override
				public View getView(int position, View convertView,
						ViewGroup parent) {
					View v = convertView;
					if (v == null) {
						LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
						v = vi.inflate(R.layout.item_sender_info, null);
					}

					SenderContactInfo contact = items.get(position);
					if (contact != null) {
						TextView tvFrom = (TextView) v
								.findViewById(R.id.tvFrom);
						TextView tvDate = (TextView) v
								.findViewById(R.id.tvDate);
						TextView tvTime = (TextView) v
								.findViewById(R.id.tvTime);
						TextView tvNote = (TextView) v
								.findViewById(R.id.tvNote);
						CheckBox CheckBox01 = (CheckBox) v
								.findViewById(R.id.CheckBox01);

						CheckBox01.setChecked(contact.isChecked());
						tvFrom.setText("From: " + contact.getSender());
						tvDate.setText("Date: " + contact.getDate());
						tvTime.setText("Time: " + contact.getTime());
						tvNote.setText("Notes: " + contact.getNote());
					}
					return v;
				}
			};
		} catch (Exception e) {
			new AlertDialog.Builder(this).setMessage(
					"error: inbox contact " + e.getMessage()).show();
		}
		if (items.isEmpty()) {
			((TextView) findViewById(R.id.tvMessageEmptyList))
					.setText(R.string.msg_EmptyListContact);
		} else {
			((TextView) findViewById(R.id.tvMessageEmptyList)).setText("");
		}
		lv.setAdapter(aa);
		lv.setOnItemClickListener(this);
	}

	public void checkItemClick(View v) {
		int pos = lv.getPositionForView(v);
		items.get(pos).setChecked(((CheckBox) v).isChecked());
	}

	@Override
	protected void onRestart() {
		onCreate(getIntent().getExtras());
		super.onRestart();
	}

	public void AddContactClick(View v) {
		if (items.isEmpty()) {
			Toast.makeText(this, "Don't have any contacts to add",
					Toast.LENGTH_LONG);
			return;
		}
		boolean hasCheck = false;
		for (SenderContactInfo sender : items) {
			if (sender.isChecked()) {
				hasCheck = true;
				break;
			}
		}
		if (hasCheck) {
			final ProgressDialog pd = Dialog.showProgressDialog(null,
					"Please waiting...", false);
			new AddContactThread(pd).start();
		} else {
			Toast.makeText(this, R.string.msg_EmptyListContact,
					Toast.LENGTH_LONG);
		}
	}

	Handler addContactHandler = new Handler();

	public void setState(final ProgressDialog pd, final String msg) {
		addContactHandler.post(new Runnable() {

			@Override
			public void run() {
				pd.setMessage(msg);
			}
		});
	}

	public void notifyDataSetChanged(final ProgressDialog pd) {
		addContactHandler.post(new Runnable() {

			@Override
			public void run() {
				aa.notifyDataSetChanged();
				pd.dismiss();
			}
		});
	}

	class AddContactThread extends Thread {

		ProgressDialog pd;

		public AddContactThread(ProgressDialog pd) {
			this.pd = pd;
		}

		public void run() {

			for (int j = 0; j < items.size(); j++) {
				SenderContactInfo sender = items.get(j);
				if (sender.isChecked()) {
					try {
						ArrayList<Contact> myContacts = WSF
								.getPakageContact(sender.getId());
						Log.i("Size package contact", "" + myContacts.size());
						for (int i = 0; i < myContacts.size(); i++) {
							final Contact contact = myContacts.get(i);
							if (cp
									.findContactWithName(contact
											.getDisplayName()) == 0) {
								cp.writeContact(contact);
								myContacts.remove(i);
								setState(pd, "Saving '"
										+ contact.getDisplayName()
										+ "'.\nRemain: "
										+ (myContacts.size() - i)
										+ " contact(s)");
								i--;
							} else {
								addContactHandler.post(new Runnable() {

									@Override
									public void run() {
										Toast.makeText(SenderContactListActivity.this, "Contact '"
												+ contact.getDisplayName()
												+ "' has been existed",
												Toast.LENGTH_LONG);
									}
								});
							}
						}
						if (myContacts.isEmpty()) {
							WSF.deleteSender(sender.getId());
							items.remove(j);
							j--;
						} else {
							WSF
									.updateContentSender(MyXStream
											.toXML(myContacts), sender.getId());
						}
						notifyDataSetChanged(pd);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	public void DeleteContactClick(View v) {
		if (items.isEmpty()) {
			Toast.makeText(this, R.string.msg_EmptyListContact,
					Toast.LENGTH_LONG);
			return;
		}
		boolean hasCheck = false;
		for (SenderContactInfo sender : items) {
			if (sender.isChecked()) {
				hasCheck = true;
				break;
			}
		}
		if (hasCheck) {
			Dialog.show(this, "Delete Confirm",
					"Are you sure you want to delete?","Yes","No", new OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							try {
								int countDeleted = 0;
								int countCheck = 0;
								for (int i = 0; i < items.size(); i++) {
									SenderContactInfo info = items.get(i);
									if (info.isChecked()) {
										countCheck++;
										if (WSF.deleteSender(info.getId())) {
											countDeleted++;
											items.remove(i--);
										}
									}
								}
								if (countCheck > 0) {
									if (countDeleted > 0) {
										aa.notifyDataSetChanged();
									}
									if (items.isEmpty()) {
										((TextView) findViewById(R.id.tvMessageEmptyList))
												.setText(R.string.msg_EmptyListContact);
									}
									Toast.makeText(SenderContactListActivity.this, "Deleted "
											+ countDeleted
											+ (countDeleted > 1 ? " item"
													: " items"),
											Toast.LENGTH_LONG);
								} else {
									Toast.makeText(SenderContactListActivity.this, R.string.msg_WhenDontSelectContact,
											Toast.LENGTH_LONG);
								}
							} catch (Exception e) {
								Dialog.show(SenderContactListActivity.this, "Error!", e.getMessage(), null, null, null,
										null, Type.ERROR);
							}
						}
					}, new OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {dialog.dismiss();}}, Type.CONFIRM);
		} else {
			Toast.makeText(this, R.string.msg_WhenDontSelectContact,
					Toast.LENGTH_LONG);
		}
	}

	public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
		Intent intent = new Intent(this, DetailSenderContactActivity.class);
		SenderContactInfo info = items.get(pos);
		intent.putExtra("id_package", info.getId());
		startActivity(intent);
	}

}
